from datetime import datetime
import pytz
from kubernetes import client, config

# 指定配置文件路径
config.load_kube_config()

# 创建 Kubernetes API 客户端
api_instance = client.AppsV1Api()

namespaces = ['current-semester']  # 命名空间名称列表

# 遍历每个命名空间下的 Deployment 列表
for namespace in namespaces:
    deployment_list = api_instance.list_namespaced_deployment(namespace)

    # 输出命名空间名称
    print(f'NAMESPACE: {namespace}')

    # 打印表头
    print(f'{"NAME":10} {"READY":8} {"UP-TO-DATE":12} {"AVAILABLE":10} {"AGE":>5} {"CREATED AT":26}')

    # 遍历 Deployment 列表
    for deployment in deployment_list.items:
        name = deployment.metadata.name
        ready_replicas = deployment.status.ready_replicas or 0
        up_to_date_replicas = deployment.status.updated_replicas or 0
        available_replicas = deployment.status.available_replicas or 0
        created_at = deployment.metadata.creation_timestamp.timestamp()
        age = (datetime.now(pytz.utc).timestamp() - created_at) / 3600

        # 打印输出每个 Deployment 的名称、状态和年龄
        print(f'{name:10} {ready_replicas}/{deployment.spec.replicas or 0:<8} {up_to_date_replicas:<12} {available_replicas:<10} {age:>3.0f}h {datetime.fromtimestamp(created_at, pytz.utc).strftime("%Y-%m-%d %H:%M:%S %Z%z"):26}')

    # 输出分隔符
    print('-' * 100)
